#!/usr/bin/env python3
"""
Text2SQL评估系统前端启动脚本
"""
import os
import sys
import subprocess
import webbrowser
import time
import threading

def check_node():
    """检查Node.js是否安装"""
    try:
        result = subprocess.run(['node', '--version'], capture_output=True, text=True)
        if result.returncode == 0:
            print(f"✓ Node.js版本: {result.stdout.strip()}")
            return True
        else:
            print("✗ Node.js未安装或版本过低")
            return False
    except FileNotFoundError:
        print("✗ Node.js未安装")
        return False

def check_npm():
    """检查npm是否安装"""
    try:
        result = subprocess.run(['npm', '--version'], capture_output=True, text=True)
        if result.returncode == 0:
            print(f"✓ npm版本: {result.stdout.strip()}")
            return True
        else:
            print("✗ npm未安装")
            return False
    except FileNotFoundError:
        print("✗ npm未安装")
        return False

def install_dependencies():
    """安装前端依赖"""
    print("📦 安装前端依赖...")
    try:
        result = subprocess.run(['npm', 'install'], cwd='frontend', check=True)
        print("✓ 依赖安装完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ 依赖安装失败: {e}")
        return False

def start_dev_server():
    """启动开发服务器"""
    print("🌐 启动前端开发服务器...")
    try:
        subprocess.run(['npm', 'run', 'serve'], cwd='frontend')
    except KeyboardInterrupt:
        print("\n前端服务已停止")
    except Exception as e:
        print(f"✗ 启动失败: {e}")

def main():
    """主函数"""
    print("=== Text2SQL评估系统前端启动 ===")
    
    # 检查Node.js和npm
    if not check_node() or not check_npm():
        print("\n请先安装Node.js和npm:")
        print("1. 访问 https://nodejs.org/ 下载安装Node.js")
        print("2. 安装完成后重新运行此脚本")
        return
    
    # 检查frontend目录
    if not os.path.exists('frontend'):
        print("✗ 未找到frontend目录")
        return
    
    # 检查package.json
    if not os.path.exists('frontend/package.json'):
        print("✗ 未找到package.json文件")
        return
    
    # 安装依赖
    if not install_dependencies():
        return
    
    # 启动开发服务器
    print("\n🚀 前端服务启动中...")
    print("📱 访问地址: http://localhost:8080")
    print("🔄 支持热重载，修改代码后自动刷新")
    print("⏹️  按 Ctrl+C 停止服务")
    print("-" * 50)
    
    try:
        start_dev_server()
    except KeyboardInterrupt:
        print("\n👋 前端服务已停止")

if __name__ == "__main__":
    main()
